package ro.upt.dcda.pricezone.s1.requests.admin;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import ro.upt.dcda.pricezone.common.ConnectionFactory;
import ro.upt.dcda.pricezone.s1.pojo.Admin;
import ro.upt.dcda.pricezone.s1.pojo.LoggedAdmin;

public class AdminLoginRequest {

	private Admin admin;
	private String adminSid;

	/**
	 * 
	 * @param usermail
	 * @param password
	 * @return
	 */
	public boolean work(String usermail, String password) {
		Session session = ConnectionFactory.getFactory().openSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			Query query = session
					.createQuery("from Admin where email=:email and password=:password");
			query.setParameter("email", usermail);
			query.setParameter("password", password);
			List<?> list = query.list();
			if (list.size() != 1) {
				return false;
			}
			admin = (Admin) list.get(0);
			tx.commit();
		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
			return false;
		} finally {
			session.close();
		}
		login();
		return true;
	}

	public Admin getAdmin() {
		return admin;
	}

	public String getAdminSid() {
		return adminSid;
	}

	private void login() {
		Session session = ConnectionFactory.getFactory().openSession();
		Transaction tx = null;
		try {
			System.out.println("Trying to login admin.");
			tx = session.beginTransaction();
			Query q = session
					.createQuery("delete LoggedAdmin where admin_id = :admin_id");
			q.setParameter("admin_id", admin.getId());
			q.executeUpdate();
			LoggedAdmin loggedAdmin = new LoggedAdmin(admin.getId(), UUID
					.randomUUID().toString(), new Date());
			for (int i = 0; i < 10; i++) {
				try {
					session.save(loggedAdmin);
					adminSid = loggedAdmin.getSid();
					continue;
				} catch (HibernateException e) {
					e.printStackTrace();
					if (i == 9) {
						throw e;
					}
					loggedAdmin.setSid(UUID.randomUUID().toString());
				}
			}
			tx.commit();
			System.out.println("Admin login succesful.");
		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
	}
}
